import { css } from 'solid-styled-components';
import { ToolBar } from './ToolBar';
import { Show, createSignal, onMount } from 'solid-js';
import { EditorModel } from './EditorModel';
import { Config } from '../../common/config';

export function RichEditor() {
  const [editor, setEditor] = createSignal<HTMLIFrameElement>(null!);
  const model = new EditorModel();

  onMount(() => {
    const document = editor().contentDocument;
    if (!document) {
      return;
    }

    document?.body.setAttribute('contenteditable', Config.isPreview ? 'false' : 'true');
    model.setDocument(document);
  });

  return (
    <div class={styleClass}>
      {Config.isPreview}
      <Show when={!Config.isPreview}>
        <ToolBar editorFrame={editor()} model={model} />
      </Show>
      <iframe class='editor' ref={setEditor} />
    </div>
  );
}

const styleClass = css`
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  .editor {
    outline: none;
    border: none;
    background-color: aliceblue;
    flex-grow: 1;
  }
`;
